import { debug, leancloudappid, leancloudappkey } from "./app_config"
import Toast from './src/components/Toast'
import * as account from "./services/account"
import EventEmitter from "./src/common/EventEmitter.js"

// leancloud
import AV from 'leancloud-storage'
import {Realtime, TextMessage} from 'leancloud-realtime'
import {TypedMessagesPlugin, ImageMessage} from 'leancloud-realtime-plugin-typed-messages'
AV.init({ appId: leancloudappid, appKey: leancloudappkey })

export let SlothRealtime = new Realtime({
    appId: leancloudappid,
    plugins: [TypedMessagesPlugin],
    region: 'cn'
})

SlothRealtime.on('disconnect', function () {
    Toast.show("网络连接已断开", 'warn')
    SlothRealtime.retry()
})
SlothRealtime.on('retry', function (attempt) {
    Toast.show('正在进行第' + attempt + '次重连')
})
SlothRealtime.on('reconnect', function() {
    Toast.show('网络连接已恢复')
})

export let imclient = {}
export const MessageReciveEvent = "message_recive"
export const IMClientInitEvent = "imclient_init"
let MountIMClient = (user)=> {
    SlothRealtime && SlothRealtime.createIMClient(user.id).then((client) => {
        imclient = client
        EventEmitter.emit(IMClientInitEvent, null)
        imclient.on('message', (message, conv) => {
            EventEmitter.emit(MessageReciveEvent, message, conv)
        })
    })
}

let UnMountIMClient = ()=> {
    imclient = {}
}

// Services
let MountServices = ()=> {
    account.CurrentUser().then((user) => {
        MountIMClient(user)
    }).catch(() => {
        UnMountIMClient()
    })
}
MountServices()
EventEmitter.addListener(account.TokenChangedEvent, MountServices.bind(this))